﻿using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

using Microsoft.Live.Core;
using Microsoft.Live.Messenger;

namespace MessengerSample
{
    public partial class Page : UserControl
    {
        private User user;

        private List<ConversationWindow> convWindows = new List<ConversationWindow>();

        public Page()
        {
            InitializeComponent();
        }

        public void SetIdentity(Identity identity)
        {
            this.user = new User(identity);
            this.user.SignedOutRemotely += this.OnSignedOutRemotely;

            this.ContactList.DataContext = this.user;
            
            this.user.SignIn();
        }

        private void OnSignedOutRemotely(object sender, SignedOutRemotelyEventArgs e)
        {
            this.ContactList.DataContext = null;

            foreach (ConversationWindow window in this.convWindows)
            {
                window.DataContext = null;

                this.LayoutRoot.Children.Remove(window);
            }

            this.convWindows.Clear();
        }

        private void OnContactSelected(object sender, MouseButtonEventArgs e)
        {
            FrameworkElement element = e.Source as FrameworkElement;
            Debug.Assert(element != null);

            if (element != null)
            {
                Contact contact = (Contact)element.DataContext;
                Conversation conversation = this.user.Conversations.Create(contact.CurrentAddress);

                foreach (ConversationWindow window in this.convWindows)
                {
                    if (conversation == window.Conversation &&
                        conversation.Roster.Count == 2)
                    {
                        // Already exists, show
                        return;
                    }
                }

                ConversationWindow convWindow = new ConversationWindow();
                convWindow.Initialize(conversation);
                this.convWindows.Add(convWindow);
                this.LayoutRoot.Children.Add(convWindow);
            }
        }
    }
}
